package com.system.util;

import com.system.entity.Admin;
import com.system.entity.Student;
import com.system.entity.Course;
import com.system.entity.Score;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件操作工具类
 * 提供文件读写功能，实现数据持久化
 */
public class FileUtil {
    private static final String DATA_DIR = "data";

    static {
        // 确保数据目录存在
        File dir = new File(DATA_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 从文件读取数据并转换为对应实体类的数组
     * @param filePath 文件路径
     * @param clazz 实体类类型
     * @return 实体类数组
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] readFromFile(String filePath, Class<T> clazz) {
        List<T> list = new ArrayList<>();
        File file = new File(DATA_DIR + "/" + filePath);

        // 检查文件是否存在，如果不存在且是admin.txt，则创建默认管理员
        if (!file.exists()) {
            if ("admin.txt".equals(filePath)) {
                createDefaultAdmin();
                // 重新读取默认管理员数据
                file = new File(DATA_DIR + "/" + filePath);
            } else {
                // 返回对应类型的空数组，避免类型转换问题
                if (clazz == Admin.class) {
                    return (T[]) new Admin[0];
                } else if (clazz == Student.class) {
                    return (T[]) new Student[0];
                } else if (clazz == Course.class) {
                    return (T[]) new Course[0];
                } else if (clazz == Score.class) {
                    return (T[]) new Score[0];
                }
                return (T[]) new Object[0];
            }
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) continue;
                
                String[] parts = line.split(",");
                T entity = null;

                if (clazz == Admin.class && parts.length >= 2) {
                    entity = (T) new Admin(parts[0], parts[1]);
                } else if (clazz == Student.class && parts.length >= 5) {
                    entity = (T) new Student(parts[0], parts[1], parts[2], 
                            Integer.parseInt(parts[3]), parts[4]);
                } else if (clazz == Course.class && parts.length >= 3) {
                    entity = (T) new Course(parts[0], parts[1], 
                            Double.parseDouble(parts[2]));
                } else if (clazz == Score.class && parts.length >= 5) {
                    entity = (T) new Score(parts[0], parts[1], parts[2], 
                            parts[3], Double.parseDouble(parts[4]));
                }

                if (entity != null) {
                    list.add(entity);
                }
            }
        } catch (IOException e) {
            System.out.println("文件操作失败：" + e.getMessage());
        }

        // 将List转换为对应类型的数组，避免类型转换异常
        if (clazz == Admin.class) {
            return (T[]) list.toArray(new Admin[0]);
        } else if (clazz == Student.class) {
            return (T[]) list.toArray(new Student[0]);
        } else if (clazz == Course.class) {
            return (T[]) list.toArray(new Course[0]);
        } else if (clazz == Score.class) {
            return (T[]) list.toArray(new Score[0]);
        }
        
        return (T[]) list.toArray();
    }

    /**
     * 将实体类数组写入文件
     * @param filePath 文件路径
     * @param data 实体类数组
     */
    public static <T> void writeToFile(String filePath, T[] data) {
        File file = new File(DATA_DIR + "/" + filePath);
        
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            if (data == null || data.length == 0) {
                return;
            }

            for (T entity : data) {
                String line = "";
                
                if (entity instanceof Admin) {
                    Admin admin = (Admin) entity;
                    line = admin.getUsername() + "," + admin.getPassword();
                } else if (entity instanceof Student) {
                    Student student = (Student) entity;
                    line = student.getStudentId() + "," + student.getName() + "," +
                           student.getGender() + "," + student.getAge() + "," + student.getClassName();
                } else if (entity instanceof Course) {
                    Course course = (Course) entity;
                    line = course.getCourseId() + "," + course.getCourseName() + "," + course.getCredit();
                } else if (entity instanceof Score) {
                    Score score = (Score) entity;
                    line = score.getStudentId() + "," + score.getStudentName() + "," +
                           score.getCourseId() + "," + score.getCourseName() + "," + score.getScore();
                }

                if (!line.isEmpty()) {
                    writer.write(line);
                    writer.newLine();
                }
            }
        } catch (IOException e) {
            System.out.println("文件操作失败：" + e.getMessage());
        }
    }

    /**
     * 创建默认管理员账户
     */
    private static void createDefaultAdmin() {
        Admin[] admins = new Admin[1];
        admins[0] = new Admin("admin", "123456");
        writeToFile("admin.txt", admins);
    }
}